#include <iostream>
#include <stdlib.h>
#include <string.h>                     
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>                  
#include <thread>
#include <string.h>
#include <sstream>
#include <mutex>
class dbms_far
{
public:
    bool eventLoop(std::string recvbuf)
    {
        std::string sr;
        std::stringstream sring;
        sring.str(recvbuf);
    };
private:

};
#define PORT 9000
std::mutex mut;
static void* client_thread(void *arg)
{
    int recvlen = 0;
    char recvbuf[1024] = "";
    long connfd = (long)arg;
    while((recvlen = recv(connfd,recvbuf,sizeof(recvbuf),0))>0)
    {
        std::cout<<"recv_buf:"<<recvbuf<<recvlen<<std::endl;
        mut.lock();
        send(connfd, recvbuf, recvlen, 0);
        dbms_far dms;
        if(dms.eventLoop(recvbuf))     
        {

        }   
        mut.unlock();
    }
    std::cout<<"client closed"<<recvbuf<<std::endl;
    close(connfd);
    return NULL;
}

int do_do()
{
    int sockfd;
    int log;
    int connfd;
    pthread_t thread_id;
    struct sockaddr_in server,client;
    bzero(&server,sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(PORT);
    server.sin_addr.s_addr = htonl(INADDR_ANY);//在本地的
    //创建套接字
    sockfd = socket(AF_INET,SOCK_STREAM,0);
    if(sockfd < 0)
     std::cout<<"socket create error\n"<<std::endl;
    log = bind(sockfd,(struct sockaddr*)&server,sizeof(server));
    if(log < 0)
    {
        std::cout<<"bindfd error\n"<<std::endl;
        close(sockfd);
        exit(-1);
    }

    log = listen(sockfd,20);
    if(log < 0)
    {
        std::cout<<"listen error\n"<<std::endl;
        printf("listen error\n");
        close(sockfd);
        exit(-1);
    }
    std::cout<<"waiting client >>>>>"<<std::endl;

    while(1)
    {
        socklen_t client_len = sizeof(client);
        //accept
    connfd = accept(sockfd,(struct sockaddr*)&client,&client_len);
    if(connfd < 0)
    {
        std::cout<<"connfd error"<<std::endl;
        continue;
    }
    char cli_ip[INET_ADDRSTRLEN] = "";
    inet_ntop(AF_INET, &client.sin_addr, cli_ip, INET_ADDRSTRLEN);
    std::cout<<"----------------------------------------------"<<std::endl;
    printf("client ip=%s,port=%d\n", cli_ip,ntohs(client.sin_port));

    pthread_create(&thread_id,NULL,&client_thread,(void*)connfd);
    pthread_detach(thread_id);//线程分离，结束时自动回收线程
    }
    close(sockfd);
    return 0;
}
int main()
{
    do_do();
}